const express = require("express")
const router = express.Router()
const sqlQuery = require("../mysql/index.cjs")


router.post("/speak",(req,res)=>{
  let body = req.body
  let sql = `insert into comment(user_id,note_id,comment) values("${body.user_id}","${body.note_id}","${body.comment}")`
  sqlQuery(sql,msg=>{
    // console.log(msg.affectedRows);
    if(msg.affectedRows==1){
      // console.log(1111);
      res.send({
        status : 100,
        msg : "OK"
      })
    }else {
      res.send({
        status : 400,
        msg : "失败"
      })
    }
  })
})

// 评论
router.post("/com",(req,res)=>{
  let body = req.body
  let comments = []
  let sql = `select * from comment where note_id=${body.id}`
  sqlQuery(sql,message=>{
    if(message.length==0){
      res.send({
        status : 100,
        msg : "成功",
        data:comments
      })
    }else{
      // 循环获取到的评论
      message.forEach(el => {
        let sql = `select * from user where id=${el.user_id}`
        // 通过评论获取到对应的用户id
        sqlQuery(sql,msg=>{
          let {user_id,comment,time} = el
          let {name,avatar} = msg[0]
          // 将查询到的用户push到数组中
          let com = {
            user_id,comment,time,name,avatar
          }
          comments.push(com)
          // 判断查询到的的评论 和 push到数组中的长度是否一致
          // 如果一直就返回评论数组
          if(message.length==comments.length){
            res.send({
              status : 100,
              msg : "成功",
              data:comments
            })
          }
        })
      });
    }
    
  })
})



module.exports = router